package org.fhm.zdte.common.task;

import org.fhm.substrate.annotation.Component;
import org.fhm.substrate.service.LoggerHandler;
import org.fhm.substrate.standard.ILogger;
import org.fhm.zdte.common.pojo.Address;
import org.fhm.zdte.common.pool.ThreadPoolFactory;
import org.fhm.zdte.common.protocol.AbstractMessageStandard;
import org.fhm.zdte.common.service.transmission.AbstractCmd;

import java.util.Objects;


/**
 * Tasks that need to be handled by the receiver.
 *
 * @author by 月光叶
 * @since 2023/11/4
 */
@Component
public class ReceiveDealTask extends AbstractPacketDeal {

    private final ILogger logger = LoggerHandler.getLogger(ReceiveDealTask.class);

    public ReceiveDealTask(AbstractPacketDeal owner, AbstractMessageStandard message, Address address) {
        this.address = address;
        this.message = message;
        this.owner = owner;
    }

    @SuppressWarnings("unused")
    public ReceiveDealTask() {
    }

    @Override
    public void run() {
        try {
            AbstractCmd cmdExecutor = getCmdExecutor(message);
            if (Objects.isNull(cmdExecutor)) {
                logger.warn("no corresponding command actuator found");
                return;
            }
            cmdExecutor.receiveCmd(address, message);
        } catch (Exception e) {
            logger.error(e, "failed to executor task");
        }
    }

    @Override
    public void getTaskAndSubmit(AbstractMessageStandard message, Address address) {
        try {
            threadPoolFactory
                    .submitTask(
                            ThreadPoolFactory.TRANSFORM_THREAD_POOL,
                            new ReceiveDealTask(this, message, address)
                    );
        } catch (Exception e) {
            logger.error(e, "failed to submit task");
        }
    }

}
